/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.gui.mvc.view.labels;

import java.awt.Component;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import javax.swing.AbstractCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.testis.utils.tree.LabelTreeNode;

import java.util.EventObject;
import java.awt.event.ItemEvent;

/**
 *
 * @author selcuk
 */
public class LabelTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {

    TwoStateLabelNodeRenderer renderer = new TwoStateLabelNodeRenderer();
    ChangeEvent _changeEvent = null;
    JTree tree;

    public LabelTreeNodeEditor(JTree tree) {
        this.tree = tree;
    }

    @Override
    public Object getCellEditorValue() {
        JCheckBox checkbox = renderer.getLeafRenderer();
        LabelTreeNode labelTreeNode = renderer.getLabelTreeNode();
        labelTreeNode.setSelected(checkbox.isSelected());
//        LabelTreeNode labelTreeNode = new LabelTreeNode(checkbox.getText(), checkbox.isSelected());
        return labelTreeNode;
    }

    @Override
    public boolean isCellEditable(EventObject event) {
        boolean returnValue = false;
        if (event instanceof MouseEvent) {
            MouseEvent mouseEvent = (MouseEvent) event;
            TreePath path = tree.getPathForLocation(mouseEvent.getX(),
                    mouseEvent.getY());
            if (path != null) {
                Object node = path.getLastPathComponent();
                if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                    Object userObject = treeNode.getUserObject();
                    returnValue = ((!treeNode.isRoot()) && (userObject instanceof LabelTreeNode));
                }
            }
        }
        return returnValue;
    }

    @Override
    public Component getTreeCellEditorComponent(JTree tree, Object value,
            boolean isSelected, boolean expanded, boolean leaf, int row) {
        Component editor = renderer.getTreeCellRendererComponent(tree, value,
                true, expanded, leaf, row, true);

        // editor always selected / focused
        ItemListener itemListener = new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent itemEvent) {
                if (stopCellEditing()) {
                    fireEditingStopped();
                }
            }
        };

        if (editor instanceof JCheckBox) {
            ((JCheckBox) editor).addItemListener(itemListener);
        }

        return editor;
    }
}
